///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.utils {
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import sugarcookie.collections.EnhancedArrayCollection;
	import sugarcookie.error.ApplicationError;
	
	public class ObjectPool {
		private var _log:ILogger;
		private var _groups:EnhancedArrayCollection;
		
		public function ObjectPool() {
			_log = Log.getLogger("sugarcookie.utils.ObjectPool");
			_groups = new EnhancedArrayCollection();
		}
		
		public function addObject(object:*,group:String=null):void {
			if (group==null) group = "default";
			
			_log.debug("Adding object to group: "+group);
			
			if (_groups.containsKey(group)) {
				_groups.getItemAtKey(group).push(object);
			} else {
				_groups.addItemWithKey(group,new Array())
				_groups.getItemAtKey(group).push(object);
			}
		}
		
		public function getObject(group:String=null):* {
			if (group==null) group = "default";
			
			_log.debug("Getting object from group: "+group);
			
			if (_groups.getItemAtKey(group).length==0) {
				throw new ApplicationError("Group has no objects!");
				return null;
			} else {
				return _groups.getItemAtKey(group).pop();
			}
		}
	}
}